package com.ideal.wxlogin.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ideal.wxlogin.utils.ElementUtils;
import com.ideal.wxlogin.utils.RedisUtil;
import com.ideal.wxlogin.utils.RestTemplateUtil;
import jdk.nashorn.internal.parser.JSONParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: 抹茶冰冰冰
 * @Date: 2020-04-02
 * @Description: 验证消息是否来自微信服务器
 **/
@Slf4j
@Service
@RequestMapping("checkTokenService")
public class WeChatService {
    /**
     * 这里获取的是配置文件里的token的值
     */
    @Value("${wx.token}")
    private String token;

    @Value("${wx.appid}")
    private String appID;

    @Value("${wx.secret}")
    private String secret;

    @Value("${wx.timeout}")
    private int timeout;

    @Autowired
    private RedisUtil redisUtil;

    public String checkToken(
            String signature,
            String timestamp,
            String nonce,
            String echostr) {
        //放入数组，进行字典排序后组成一个字符串。
        String[] arr = new String[]{token, timestamp, nonce};
        Arrays.sort(arr);
        String str = arr[0] + arr[1] + arr[2];
        MessageDigest md = null;
        String resultMsg = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(str.getBytes());
            resultMsg = byteToStr(digest);
            resultMsg = resultMsg.toLowerCase();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if (!resultMsg.equals(signature)) {
            return "";
        }
        return echostr;

    }

    private static String byteToStr(byte[] byteArray) {
        StringBuilder strDigest = new StringBuilder();
        for (int i = 0; i < byteArray.length; i++) {
            strDigest.append(byteToHexStr(byteArray[i]));
        }
        return strDigest.toString();
    }

    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }

    public void handleWechatCallBack(String msg, String signature, String timestamp, String nonce, String echostr, String openid) {
        try {
            log.info(msg);
            log.info("openId:{}", openid);
            ElementUtils element = new ElementUtils(msg);
            String type = element.get("MsgType");
            log.info("type:{}", type);
            switch (type) {
                case "event":
                    String eventType = element.get("Event");
                    log.info("eventType:{}", eventType);
//                    String eventKey = element.get("EventKey");
//                    log.info("eventKey:{}",eventKey);
                    String ticket = element.get("Ticket");
                    log.info("ticket:{}", ticket);
                    switch (eventType) {
                        case "SCAN"://已经关注的扫码会进入这个事件
                            redisUtil.setString(ticket, openid);
                            break;
                        case "unsubscribe":
                            break;
                        case "subscribe"://关注的人会进入这个事件
                            if (ticket != null) redisUtil.setString(ticket, openid);
                            break;
                    }
            }
        } catch (Exception e) {
            log.info("handleWxCallBackMsg_error:", e);
        }
    }

    public String getAccessToken() {
        String access_token = redisUtil.getString("access_token");
        if (access_token == null) {
            log.info("access_token is null");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("grant_type", "client_credential");
            jsonObject.put("appid", appID);
            jsonObject.put("secret", secret);
            String resp = RestTemplateUtil.get("https://api.weixin.qq.com/cgi-bin/token", jsonObject);
            JSONObject obj = JSONObject.parseObject(resp);
            access_token = obj.getString("access_token");
            redisUtil.setString("access_token", access_token, 1, TimeUnit.HOURS);
        }
        return access_token;
    }

    public String getQrcode() {
        String accessToken = getAccessToken();
        String json = "{\"expire_seconds\":%d,\"action_name\":\"QR_STR_SCENE\",\"action_info\":{\"scene\":{\"scene_str\":\"%s\"}}}";
        String uuid = UUID.randomUUID().toString().replace("-", "");
        JSONObject jsonObject = JSONObject.parseObject(String.format(json, timeout, uuid));
        String resp = RestTemplateUtil.post("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken, jsonObject);
        JSONObject obj = JSONObject.parseObject(resp);
        redisUtil.setString(obj.getString("ticket"), "none", timeout, TimeUnit.SECONDS);
        return resp;
    }

    public String checkLoginStatus(String ticket) {
        return redisUtil.getString(ticket);
    }

    public void postCard() {
        String accessToken = getAccessToken();
        String body = "{ \"touser\":\"o0LaD7FDH0zmzNo7F6akKZgrpckk\", \"template_id\":\"AoQapyyM4jzco84mszQpJWf-YxVz_GlHl0Kn5fWQKJo\", \"url\":\"http://weixin.qq.com\", \"topcolor\":\"#FF0000\", \"data\":{ \"User\":{ \"value\":\"黄先生\", \"color\":\"#173177\" }, \"Date\":{ \"value\":\"06月07日 19时24分\", \"color\":\"#173177\" }, \"CardNumber\":{ \"value\":\"0426\", \"color\":\"#173177\" }, \"Type\":{ \"value\":\"消费\", \"color\":\"#173177\" }, \"Money\":{ \"value\":\"人民币260.00元\", \"color\":\"#173177\" }, \"DeadTime\":{ \"value\":\"06月07日19时24分\", \"color\":\"#173177\" }, \"Left\":{ \"value\":\"6504.09\", \"color\":\"#173177\" } } }";
        String resp = RestTemplateUtil.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken, JSONObject.parseObject(body));
        log.info("resp:{}", resp);
    }

    public void creatMenu() {
        String accessToken = getAccessToken();
        String body = "{ \"button\":[ { \"type\":\"click\", \"name\":\"今日歌曲\", \"key\":\"V1001_TODAY_MUSIC\" }, { \"name\":\"菜单\", \"sub_button\":[ { \"type\":\"view\", \"name\":\"搜索\", \"url\":\"http://www.soso.com/\" }, { \"type\":\"miniprogram\", \"name\":\"wxa\", \"url\":\"http://mp.weixin.qq.com\", \"appid\":\"wx286b93c14bbf93aa\", \"pagepath\":\"pages/lunar/index\" }, { \"type\":\"click\", \"name\":\"赞一下我们\", \"key\":\"V1001_GOOD\" }] }] }";
        String resp = RestTemplateUtil.post("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken, JSONObject.parseObject(body));
        log.info("resp:{}", resp);
    }
}